import React, { Component } from 'react';
import { Card, Select, Input, Button, Table, Pagination, Form } from 'antd';
import { PlusOutlined } from '@ant-design/icons';

import {
  findCommoditiesRequest,
  updateStatusByIdRequest,
  searchCommodityByName,
  searchCommodityByDesc,
} from '../../../../api/index';
import './commodity-home.css';

const PAGE_SIZE = 4;

export default class commodityHome extends Component {
  constructor(props) {
    super(props);
    this.initColumns();
    this.state = {
      currentPage: 1,
      commodities: [],
      isLoading: true,
      totalSize: 0,
      isOnSubPage: false,
    };
    this.getCommodities();
    this.formRef = React.createRef();
  }

  componentDidMount() {
    this.setState({ isLoading: false });
  }

  getCommodities = async (pageNum = 1, pageSize = PAGE_SIZE) => {
    let result;
    if (!this.state.isOnSubPage) {
      result = await findCommoditiesRequest(pageNum, pageSize);
    } else {
      const searchForm = this.formRef.current.getFieldValue();
      if (!searchForm.key) {
        result = await findCommoditiesRequest(pageNum, pageSize);
        this.setState({ isOnSubPage: false });
      } else {
        switch (searchForm.searchWay) {
          case '1':
            result = await searchCommodityByName(
              searchForm.key,
              pageNum,
              pageSize
            );
            break;
          case '2':
            result = await searchCommodityByDesc(
              searchForm.key,
              pageNum,
              pageSize
            );
            break;
          default:
            result = await searchCommodityByName(
              searchForm.key,
              pageNum,
              pageSize
            );
        }
      }
    }
    if (result) {
      const commodities = result.list;
      const totalSize = result.total;
      this.setState({ commodities, totalSize });
    }
  };

  updateStatusOfCommodity = async (id, status = 0) => {
    this.setState({ isLoading: true });
    const result = await updateStatusByIdRequest(id, status);
    if (result === 1) {
      this.getCommodities(this.state.currentPage, PAGE_SIZE);
    }
    this.setState({ isLoading: false });
  };

  initColumns = () => {
    this.columns = [
      {
        title: '商品名称',
        dataIndex: 'name',
        align: 'center',
        key: 'name',
      },
      {
        title: '商品描述',
        width: '50%',
        align: 'center',
        dataIndex: 'desc',
        key: 'desc',
      },
      {
        title: '价格',
        width: '10%',
        align: 'center',
        dataIndex: 'price',
        render: (price) => '￥' + price,
        key: 'price',
      },
      {
        title: '状态',
        width: '9%',
        align: 'center',
        render: (commodity) => {
          if (commodity.status == null || commodity.status < 1) {
            return (
              <span>
                <Button
                  onClick={() => this.updateStatusOfCommodity(commodity.id, 1)}
                  type="primary"
                >
                  上架
                </Button>
                <div>停售</div>
              </span>
            );
          } else {
            return (
              <span>
                <Button
                  onClick={() => this.updateStatusOfCommodity(commodity.id, 0)}
                  type="primary"
                >
                  下架
                </Button>
                <div>在售</div>
              </span>
            );
          }
        },
      },
      {
        title: '操作',
        width: '9%',
        align: 'center',
        render: (commodity) => (
          <span>
            <Button onClick={() => this.showDetailPage(commodity)} type="link">
              详情
            </Button>
            <Button onClick={null} type="link">
              修改
            </Button>
          </span>
        ),
      },
    ];
  };

  onPaginationChange = (page, pageSize) => {
    this.setState({ isLoading: true, currentPage: page }, () => {
      this.getCommodities(page, pageSize);
    });
    this.setState({ isLoading: false });
  };

  onFinish = () => {
    this.setState({ isLoading: true, isOnSubPage: true }, () => {
      this.getCommodities(1);
    });
    this.setState({ isLoading: false });
  };

  returnPage = () => {
    this.setState({ isLoading: true, isOnSubPage: false }, () => {
      this.getCommodities();
    });
    this.setState({ isLoading: false });
    this.formRef.current.resetFields();
  };

  showDetailPage = (commodityData) => {
    this.props.history.push('/commodity-manage/detail', commodityData);
  };

  showAddPage = () => {
    this.props.history.push('/commodity-manage/add');
  };

  render() {
    const { commodities, loading, totalSize, currentPage, isOnSubPage } =
      this.state;

    const title = (
      <div className="home-title-container">
        <Form
          ref={this.formRef}
          initialValues={{ searchWay: '1' }}
          className="home-title"
          onFinish={this.onFinish}
        >
          <Form.Item className="form-select" name="searchWay">
            <Select placeholder="搜索方式">
              <Select.Option value="1">按名称搜索</Select.Option>
              <Select.Option value="2">按描述搜索</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item className="form-input" name="key">
            <Input placeholder="关键字" />
          </Form.Item>
          <Form.Item className="form-button">
            <Button type="primary" htmlType="submit">
              搜索
            </Button>
          </Form.Item>
          <div className="form-return">
            {isOnSubPage ? (
              <Button onClick={this.returnPage} type="primary">
                返回
              </Button>
            ) : null}
          </div>
        </Form>
      </div>
    );

    const extra = (
      <Button onClick={this.showAddPage} icon={<PlusOutlined />} type="primary">
        添加商品
      </Button>
    );
    return (
      <div className="home-container">
        <Card className="commodity-home-container" title={title} extra={extra}>
          <Table
            isLoading={loading}
            rowKey="id"
            bordered={true}
            dataSource={commodities}
            pagination={false}
            columns={this.columns}
          />
          <Pagination
            className="home-pagination"
            showQuickJumper
            current={currentPage}
            defaultPageSize={PAGE_SIZE}
            showSizeChanger={false}
            total={totalSize}
            onChange={this.onPaginationChange}
          />
        </Card>
      </div>
    );
  }
}
